package com.core.ui.customtag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.core.protocols.IActionBarDatasource;
import com.core.ui.customview.ActionBarItemView;

public class ActionBarView
        extends TagSupport {

	private static final long    serialVersionUID = 1L;
	private IActionBarDatasource datasource       = null;



	public IActionBarDatasource getDatasource () {

		return datasource;
	}



	public void setDatasource ( IActionBarDatasource datasource ) {

		this.datasource = datasource;
	}



	@Override
	public void release () {

		datasource = null;
		super.release();
	}



	public int doStartTag ()
	        throws JspException {

		try {

			if ( datasource == null ) {
				return SKIP_BODY;
			}

			datasource.reloadData();

			StringBuilder sb = new StringBuilder();

			int numberOfItems = datasource.itemsCount();
			if ( numberOfItems > 0 ) {

				sb.append("<div class=\"action_bar_navigator\">");

				for ( int i = 0; i < numberOfItems; i++ ) {
					ActionBarItemView actionBarItem = datasource.itemAtIndex(i);
					if ( actionBarItem != null ) {
						sb.append(actionBarItem.toString());
					}
				}
				sb.append("</div>");
			} else {
				sb.append(" ");
			}

			JspWriter writer = pageContext.getOut();

			writer.write(sb.toString());
		} catch ( IOException e ) {
			throw new JspException(e.getMessage());

		}

		return SKIP_BODY;
	}

}
